package com.uziot.bucket.guava.lock;

import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author shidt
 * @version V1.0
 * @className GuavaLock
 * @date 2020-04-07 17:04:24
 * @description
 */
@Slf4j
public class GuavaLock {

    @Resource
    private Cache<String, String> cache;


    /**
     * 锁，key和放置的值，不允许KEY和val任何一个是为null,否则锁定失败
     *
     * @param key key
     * @return 是否成功
     */
    public boolean lock(String key, String val) {
        if (key == null || val == null) {
            return false;
        }
        if (cache.getIfPresent(key) == null) {
            cache.put(key, val);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 锁，key和放置的值，不允许KEY和val任何一个是为null,否则锁定失败
     *
     * @param key key
     * @return 是否成功
     */
    public boolean lock(String key) {
        if (key == null) {
            return false;
        }
        if (cache.getIfPresent(key) == null) {
            cache.put(key, "");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 解锁
     *
     * @param key key
     */
    public void unlock(String key) {
        if (key != null) {
            cache.invalidate(key);
        }
    }


}
